// base
import Taro, { Component } from '@tarojs/taro'
import { View, Text, Input, Textarea } from '@tarojs/components'
// redux
import { connect } from '@tarojs/redux'
import { DOREQUESTCHOOSEJOBINPUT } from './store/actions/pagechoosejobinput'
import { UPDATEPAGECHOOSEJOBINPUT } from './store/types/pagechoosejobinput'
// less
import './index.less'

// componnet
import Settlement from './components/settlement'
// libs
import { getGlobalData } from '../../configuration/globaldata'
import { showToast } from '../../crossplatform/apiservice/toast'
import { setNavigationBarTitle } from '../../crossplatform/apiservice/setNavigation'
import { navigateBack } from '../../crossplatform/apiservice/navigate'
import { editSelfEvaluation } from '../../service/user-info-controller'
import CompanyList from './components/company-list'
import { getMajorList } from '../../service/city-controller'
import { searchListRequest } from '../../service/tian-yan-cha-controller'
import If from '../../components/page-components/if'

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGECHOOSEJOBINPUT,
      payload: {
        ...payload
      }
    })
  }
})

@connect(
  ({ pagechoosejobinput, userinfo }) => ({
    ...pagechoosejobinput,
    userId: userinfo.userId,
    openId: userinfo.openId
  }),
  mapActiontoProps
)
class ChooseJobInput extends Component {
  constructor(props) {
    super(props)
    this.state = {
      inputValue: '', // 输入信息
      unitValue: '', // 薪资水平
      settlementValue: '', // 薪水结算方式
      findSchoolList: []
    }
  }
  componentWillMount() {
    // onLoad
    setNavigationBarTitle({ title: `人职初` })
    const { type } = this.$router.params
    const {
      inputData: { value, settlement, partUnit }
    } = this.props
    if (type === 'workContent') {
      this.setState({
        inputValue: (value || '【工作内容】\n\n\n【工作要求】\n\n\n【人员要求】\n\n').toString(),
        settlementValue: settlement && settlement.value >= 0 ? settlement.value : '',
        unitValue: partUnit && partUnit.value >= 0 ? partUnit.value : ''
      })
    } else {
      this.setState({
        inputValue: (value || '').toString(),
        settlementValue: settlement && settlement.value >= 0 ? settlement.value : '',
        unitValue: partUnit && partUnit.value >= 0 ? partUnit.value : ''
      })
    }
  }

  componentDidMount() {
    // onready
    this.getMajorList()
  }

  componentDidShow() {
    // onshow
    this.props.updateState({
      companyList: []
    })
  }

  componentDidHide() {
    // onhide
  }

  componentWillUnmount() {
    // onUnload
  }

  queryWrap = () => {}

  onReload = () => {}

  onChange = event => {
    const value = event.detail.value
    const params = this.$router && this.$router.params
    const pageType = params.pageType

    if (pageType) {
      if (pageType == 'major') {
        let { companyList } = this.props
        console.log(pageType, 'pageType')
        if (companyList && companyList.length > 0) {
          console.log(pageType, 'paegeType')
          let reg = this.generateFuzzyQuery(value)
          let arr = []
          companyList.forEach(item => {
            let newItem = {}
            if (reg.test(item)) {
              newItem.name = item
              arr.push(newItem)
            }
          })
          this.setState({
            findSchoolList: arr,
            inputValue: value
          })
        }
      } else if (pageType == 'company') {
        this.getCompanyList({ value })
      }
    } else {
      this.setState({
        inputValue: value
      })
    }
  }
  generateFuzzyQuery = value => {
    return new RegExp(`(.*)(${value.split('').join(')(.*)(')})(.*)`, 'i')
  }
  getMajorList = () => {
    getMajorList().then(({ data } = {}) => {
      let dataentry = (data && data.entry) || []
      this.props.updateState({
        companyList: dataentry
      })
    })
  }

  getCompanyList = ({ value }) => {
    const { openId } = this.props
    searchListRequest({ keyword: value, openId: openId }).then(({ data = {} } = {}) => {
      const items = data && data.entry

      if (items && items.length) {
        items.map(data => {
          data.name = data.name.replace(/\<em\>|\<\/em\>/g, '')
        })
      }
      console.log(items, 'itemsitems')
      this.setState({
        findSchoolList: items || [],
        inputValue: value
      })
    })
  }
  onChooseCompany = ({ id, name }) => {
    const params = this.$router && this.$router.params
    if (params.pageType == 'major' || params.pageType == 'company') {
      this.chooseMajorSingle({ id, name })
    } else {
    }
  }

  chooseMajorSingle = ({ id, name }) => {
    if (name) {
      this.setState(
        {
          inputValue: name
        },
        () => {
          this.saveClick()
        }
      )
    }
  }

  saveClick = () => {
    const {
      inputData: { settlement }
    } = this.props
    const { self, archiveId } = this.$router && this.$router.params
    // 不是自我评价
    if (settlement) {
      this.settlementOnClick()
      return
    }
    const blockWords = getGlobalData('blockWords')
    const { inputValue } = this.state
    if (blockWords.test(inputValue.replace(/\s+/g, ''))) {
      showToast({
        title: '非法信息'
      })
      return
    }
    if (!self) {
      this.props.updateState({
        inputData: {
          ...this.props.inputData,
          value: inputValue
        }
      })
      navigateBack()
    } else {
      // 自我评价 直接调用存储接口
      const { userId } = this.props
      if (inputValue) {
        editSelfEvaluation({
          userId: parseInt(userId),
          selfEvaluation: inputValue,
          archiveId
        }).then(({ data }) => {
          const { status, message } = data
          if (status) {
            navigateBack()
          } else {
            showToast({
              title: message || '保存失败'
            })
          }
        })
      } else {
        showToast({
          title: '信息不能为空'
        })
      }
    }
  }
  settlementChange = settlementValue => {
    this.setState({
      settlementValue
    })
  }
  unitChange = unitValue => {
    this.setState({
      unitValue
    })
  }
  settlementOnClick = () => {
    const { inputValue, settlementValue, unitValue } = this.state
    const value = parseInt(inputValue)
    if (
      value &&
      parseInt(settlementValue) >= 0 &&
      /(^[1-9]\d*$)/.test(~~value) &&
      parseInt(unitValue) >= 0
    ) {
      this.props.updateState({
        inputData: {
          ...this.props.inputData,
          value: ~~value,
          settlement: {
            ...this.props.inputData.settlement,
            value: settlementValue
          },
          partUnit: {
            ...this.props.inputData.partUnit,
            value: unitValue
          }
        }
      })
      navigateBack()
    } else {
      showToast({
        title: '输入或选择不正确'
      })
    }
  }
  render() {
    const {
      inputData: { name, componenttype, tip, maxLength = -1, settlement, partUnit }
    } = this.props
    const { inputValue, settlementValue, findSchoolList, unitValue } = this.state
    return (
      <View className="ChooseJobInput_id31827" onClick={this.queryWrap}>
        <View className="name-wrap">
          <Text className="name">{name}</Text>
          <View className="button" onClick={this.saveClick}>
            保存
          </View>
        </View>
        <View className="tips-wrap">
          <Text className="tips">{tip}</Text>
          {maxLength && maxLength > 0 && (
            <Text className="limit">
              {inputValue.length}/{maxLength}
            </Text>
          )}
        </View>
        <View>
          {componenttype == 'textarea' ? (
            <Textarea
              placeholder-class="place-holder"
              placeholder={`请输入${name}`}
              auto-height="true"
              className="textareals"
              value={inputValue}
              onInput={this.onChange}
              maxlength={maxLength}
            />
          ) : (
            <View className="input-container">
              <Input
                placeholder-class="place-holder"
                placeholder={`请输入${name}`}
                type={settlement ? 'number' : 'text'}
                className={`inputls ${settlement ? 'din' : ''}`}
                value={inputValue}
                onInput={this.onChange}
                maxlength={parseInt(maxLength)}
                focus
              />
            </View>
          )}
        </View>
        <View>
          {settlement && (
            <Settlement
              datasource={settlement.list}
              value={parseInt(settlementValue)}
              partUnitList={partUnit.list}
              partUnitValue={parseInt(unitValue)}
              onSettlementChange={this.settlementChange}
              onUnitChange={this.unitChange}
            />
          )}
        </View>

        <If visible={findSchoolList && findSchoolList.length > 0}>
          <CompanyList dataSource={findSchoolList} onChooseCompany={this.onChooseCompany} />
        </If>
      </View>
    )
  }
}

export default ChooseJobInput
